package com.zh.juc.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zhanghuan
 * @date: 2022/10/11 20:22
 * @description: create it
 *
 * 中断只是一种协商机制，修改中断标志位不会立刻stop
 */
public class InterruptDemo3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t 中断标志位："
                            + Thread.currentThread().isInterrupted() + "程序停止");
                    break;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                } catch (InterruptedException e) {
                    // 为什么在异常初，再调一次？
                    /**
                     * 抛出InterruptedException 将会把中断状态清除，并且会报InterruptedException异常，中断标志位false,导致无限循环
                     */
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
                System.out.println("----hello");
            }
        }, "t1");
        t1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();


    }
}
